package com.bosui.ycweb;

import static android.os.Build.VERSION_CODES.KITKAT;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.OnReceiveContentListener;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebView;
import com.ycbjie.webviewlib.InterWebListener;
import com.ycbjie.webviewlib.ProgressWebView;
import com.ycbjie.webviewlib.WebProgress;
import com.ycbjie.webviewlib.X5WebUtils;
import com.ycbjie.webviewlib.X5WebView;
import com.ycbjie.webviewlib.X5WebViewClient;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements JsBridge {

    final static int COUNTS = 6;//点击次数
    final static long DURATION = 3 * 1000;//规定有效时间
    long[] mHits = new long[COUNTS];
    //    String url_net = "http://192.168.1.211";
//    String url_net = "http://192.168.1.230";
    public static String url_net = "192.168.1.100";
    //    String url_net = "http://192.168.0.230";
    //    String url_net = "http://www.baidu.com";
    String reloadUrl = "";
    private X5WebView mWebView;
    private ProgressWebView progressWebView;
    private WebProgress mProgress;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            loadUrl();
        }
    };

    private InterWebListener interWebListener = new InterWebListener() {
        @Override
        public void hindProgressBar() {
            LogUtils.d("hindProgressBar");
            mProgress.setVisibility(View.GONE);
        }

        @Override
        public void showErrorView(@X5WebUtils.ErrorType int type) {
            //设置自定义异常错误页面
            LogUtils.e("showErrorView" + type);
            if (type == X5WebUtils.ErrorMode.RECEIVED_ERROR) {//1003
                return;
            }

        }

        @Override
        public void startProgress(int newProgress) {
            //该方法是是监听进度条进度变化的逻辑
            LogUtils.d("startProgress" + newProgress);
            if (newProgress != 100) {
                mProgress.show();
            }
            mProgress.setWebProgress(newProgress);
        }

        @Override
        public void showTitle(String title) {
            //该方法是监听h5中title
            LogUtils.d("showTitle");
        }


    };
    private String TAG = "pengyl";
//    private LinearLayout ll_eth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PrefUtil.init(getApplicationContext());

        url_net = PrefUtil.getDefault().getString("ip", url_net);

        mWebView = findViewById(R.id.web_view);
//        ll_eth = findViewById(R.id.ll_eth);
//        ll_eth.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
//                intent.putExtra("extra_prefs_show_button_bar", true);//是否显示button bar
//                intent.putExtra("extra_prefs_set_next_text", "完成");
//                intent.putExtra("extra_prefs_set_back_text", "返回");
//                startActivity(intent);
//            }
//        });

        findViewById(R.id.progress);

        mProgress = findViewById(R.id.progress);
        // 显示
        mProgress.setProgress(50);              // 设置进度
        mProgress.setColor("#D81B60");             // 设置颜色
//        mProgress.setColor("#00D81B60", "#D81B60"); // 设置渐变色

        mProgress.setColor(this.getResources().getColor(R.color.purple_200),
                this.getResources().getColor(R.color.purple_700));

        //是否开启软硬件加速
        mWebView.setOpenLayerType(false);
        //设置缓存模式
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(false);
//        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.setSavePassword(false);

//        ProgressWebView progressWebView = findViewById(R.id.web_view);
//        progressWebView.getWebView().loadUrl(url_net);

        X5WebViewClient webViewClient = new X5WebViewClient(mWebView, this) {

            @Override
            public void onPageStarted(WebView webView, String url, Bitmap bitmap) {
                super.onPageStarted(webView, url, bitmap);
                LogUtils.d("onPageStarted " + url);
//                ll_eth.setVisibility(View.GONE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LogUtils.d("onPageFinished " + url);
//                String str = "android data";
//                view.loadUrl("javascript:if(window.remote){window.remote('" + str + "')}");

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Toast.makeText(MainActivity.this, "shouldOverrideUrlLoading", Toast.LENGTH_SHORT).show();

                LogUtils.d(TAG, "shouldOverrideUrlLoading" + "\n" + Uri.parse(url).getHost());
                WebView.HitTestResult hit = view.getHitTestResult();
                //hit.getExtra()为null或者hit.getType() == 0都表示即将加载的URL会发生重定向，需要做拦截处理
                if (TextUtils.isEmpty(hit.getExtra()) || hit.getType() == 0) {
                    //通过判断开头协议就可解决大部分重定向问题了，有另外的需求可以在此判断下操作
                    LogUtils.e(TAG, "重定向: " + hit.getType() + " && EXTRA（）" + hit.getExtra() +
                            "------");
                    LogUtils.e(TAG,
                            "GetURL: " + view.getUrl() + "\n" + "getOriginalUrl()" + view.getOriginalUrl());
                    LogUtils.e(TAG, "URL: " + url);
                }

                if (url.startsWith("http://") || url.startsWith("https://")) {//加载的url是http/https
                    // 协议地址
                    LogUtils.d(TAG, "http协议 url = " + url);
                    view.loadUrl(url);
                    return false; //返回false表示此url默认由系统处理,url未加载完成，会继续往下走
                } else { //加载的url是自定义协议地址
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        LogUtils.e(TAG, "URL:自定义协议地址 " + url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }

//                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description,
                                        String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                LogUtils.e("onReceivedError" + view.getUrl() + "\n" + failingUrl);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request,
                                        WebResourceError error) {
                super.onReceivedError(view, request, error);
                LogUtils.e("onReceivedError 主页面加载出现错误时，才会回调这个方法。这正是展示加载错误页面最合适的方法。" + "\n" + error.getErrorCode());

                reloadUrl = request.getUrl().toString();
                LogUtils.d("url = " + reloadUrl);

                Toast.makeText(MainActivity.this, reloadUrl + " :load fail", Toast.LENGTH_SHORT).show();

                view.loadUrl("file:///android_asset/error.html");

//                ll_eth.setVisibility(View.VISIBLE);
//                String data = "Page NO FOUND！";
//                view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\"");
//                view.loadUrl("about:blank");

            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request,
                                            WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                LogUtils.e("onReceivedHttpError");

            }
        };

        mWebView.getX5WebChromeClient().setWebListener(interWebListener);
//        mWebView.getX5WebViewClient().setWebListener(interWebListener);
        mWebView.setWebViewClient(webViewClient);

        mWebView.setWebContentsDebuggingEnabled(true);
        mWebView.addJavascriptInterface(new ImoocJsInterface(this), "launcher");


        loadUrl();

        View view_click = findViewById(R.id.view_click);

        TextView fresh = findViewById(R.id.fresh);
        fresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadUrl();
            }
        });

        view_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
                    Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                    startActivityForResult(intent, 1);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {
            url_net = PrefUtil.getDefault().getString("ip", url_net);
            mHandler.sendEmptyMessageDelayed(1, 50);
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public void loadUrl() {
        mWebView.loadUrl("http://" + url_net);
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
        }
        super.onDestroy();
    }

    @Override
    public synchronized void setTextViewValue(String value) {

        try {
            Thread.sleep(200);
            mHandler.sendEmptyMessage(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void jumpEthernet() {
        Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
        intent.putExtra("extra_prefs_show_button_bar", true);//是否显示button bar
        intent.putExtra("extra_prefs_set_next_text", "完成");
        intent.putExtra("extra_prefs_set_back_text", "返回");
        startActivity(intent);
    }
}